{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[2., 4.],\n",
      "        [6., 8.]])\n"
     ]
    }
   ],
   "source": [
    "x = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True)\n",
    "y = x**2  # y 是 2x2 矩阵\n",
    "\n",
    "gradient = torch.ones_like(y)  # 需要与 y 形状相同\n",
    "y.backward(gradient=gradient)\n",
    "\n",
    "print(x.grad)  # dy/dx = 2x\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
